import Phaser from "phaser";
import pika from '@/assets/img/pika.png';

export default class Loading extends Phaser.Scene {

    readonly LOAD_EVENTS = Phaser.Loader.Events;
    private loadingContainer!: Phaser.GameObjects.Container;

    constructor() {
        super("loading");
    }

    preload() {
        // 设置背景颜色为蓝色
        this.cameras.main.setBackgroundColor(0xa8d4bf);
        this.handleLoading();

        this.load.image("pika", pika);
        // this.load.text("startIcon", "开始");
        this.loadingContainer.setVisible(true);
    }

    async create() {
        this.destroyLoading();
        
        let startIcon = this.add.text(this.cameras.main.width / 2, this.cameras.main.height / 2, "开始")
            .setOrigin(0.5);
        // 为 startIcon 添加交互事件，使其可点击
        startIcon.setInteractive();
        startIcon.on('pointerover', () => {
            startIcon.setColor('#FF0000'); // 悬停时将字体颜色变更为红色
        });
        startIcon.on('pointerdown', () => {
            this.children.removeAll(true);
            // 可在此处添加点击后的具体逻辑
            this.scene.start("battle");
        });
    }

    handleLoading() {
        const width = this.cameras.main.width;
        const height = this.cameras.main.height;

        // 创建进度条背景
        const progressBox = this.add.graphics();
        progressBox.fillStyle(0x222222, 0.8);
        progressBox.fillRoundedRect(-160, -15, 320, 30, 10);

        const progressBar = this.add.graphics();

        // 添加百分比文字
        const percentText = this.add.text(0, 0, '0%', {
            font: '18px monospace',
            color: '#ffffff'
        }).setOrigin(0.5);

        // 添加资源名文字
        const assetText = this.add.text(0, 40, '', {
            font: '14px monospace',
            color: '#ffffff'
        }).setOrigin(0.5);

        // 创建 Container 并添加所有元素
        this.loadingContainer = this.add.container(width / 2, height / 2, [
            progressBox,
            progressBar,
            percentText,
            assetText
        ]);

        this.load.once(this.LOAD_EVENTS.START, () => {
            console.log("start");
        });
        this.load.on(this.LOAD_EVENTS.PROGRESS, (progress: number) => {
            console.log(`Loading progress: ${progress.toFixed(2)}%`);
            progressBar.clear();
            progressBar.fillGradientStyle(0xffffff, 0xa0a0a0, 0xffffff, 0xa0a0a0, 0, 0.5, 1, 0.5);
            progressBar.fillRoundedRect(-150, -10, 300 * progress, 20, 10);
            percentText.setText(`${Math.floor(progress * 100)}%`);
        });
        this.load.on(this.LOAD_EVENTS.FILE_LOAD, (key: string) => {
            console.log(`File ${key} Loading`);
            assetText.setText(`Loading: ${key}`);
        });
    }

    destroyLoading() {
        this.load.off(this.LOAD_EVENTS.PROGRESS);
        this.load.off(this.LOAD_EVENTS.FILE_COMPLETE);
        this.load.off(this.LOAD_EVENTS.COMPLETE);
        this.loadingContainer.setVisible(false);
    }
}